package com.luo.gmall.index.config;

import com.luo.gmall.index.feign.GmallPmsClient;
import com.luo.gmall.pms.entity.CategoryEntity;
import org.redisson.RedissonBloomFilter;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Zoro
 * @date 2021年11月17
 */
@Component
public class BloomFilterConfig {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private GmallPmsClient gmallPmsClient;

    private static final String REDIS_PREFIX = "index:category:";

    @Bean
    public RBloomFilter<Object> bloomFilter() {
        // 创建布隆过滤器对象
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("bloomFilter");
        // 设置布隆过滤器预插入设置
        bloomFilter.tryInit(20000, 0.03);
        List<CategoryEntity> categoryEntities = gmallPmsClient.queryTopCategoriesByParentId(0L).getData();
        // 添加布隆过滤器数据
        if (!CollectionUtils.isEmpty(categoryEntities)) {
            categoryEntities.forEach(categoryEntity -> bloomFilter.add(REDIS_PREFIX + categoryEntity.getId()));
        }
        return bloomFilter;
    }
}
